package com.wwwc.index.web.servlet;

import java.io.*;
import java.security.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;

public class UserRegisterBean {
    private EJBDatabaseQuery ejbdb;
    private HttpServletRequest request;
    private String call_path;
    private String mid;
 
    UserRegisterBean (HttpServletRequest rq,String mid) {
	this.request = rq;
	this.mid     = mid;
	this.call_path = rq.getContextPath()+rq.getServletPath();
    }
 
    public StringBuffer registerUser (String simg_key, String error_call_back, String saved_call_back) {
	HttpSession session = request.getSession(true);
	StringBuffer error = null;
	StringBuffer sbf = new StringBuffer ();
	String submit   = request.getParameter("B1");
	String pass1    = "";
	String pass2    = "";
	String user     = "";
	String email    = "";
	String fname    = "";
	String lname    = "";
	String zip      = "";
	String month    = "";
	String day      = "";
	String year     = "";
	String gender   = "";
	String user_edu = "";
	String img_key  = "";

	if(submit != null) {
	    try {
		
		String form_id = request.getParameter("submit_id");
		if(form_id == null || !form_id.equals(session.getAttribute("submit_id"))) {
		    return sbf.append("&nbsp;");
		}

		String user_ip = request.getRemoteAddr();

		pass1    = request.getParameter("pass_word1");
		pass2    = request.getParameter("pass_word2");
		user     = request.getParameter("user_name");		
		email    = request.getParameter("user_email");
		fname    = request.getParameter("user_fname");
		lname    = request.getParameter("user_lname");
		zip      = request.getParameter("user_zip");
		month    = request.getParameter("op_age_month");
		day      = request.getParameter("op_age_day");
		year     = request.getParameter("op_age_year");
		gender   = request.getParameter("op_sex");
		user_edu = request.getParameter("op_edu");
		img_key  = request.getParameter("img_key");
		
		String format1 = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwxyz-'";
		String format2 =format1+"_0123456789.";

		MyUserInputCheck ck = new MyUserInputCheck();
		if(!ck.checkFormat("Username", user, format2)) {
		    error = ck.getMessage();
		}

		if(error == null && !ck.checkSize("Username", user , 5, 20)) {
		    error = ck.getMessage();
		}

		if (ejbdb == null) {
		    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		}

		String query = null;
		String temp  = null;

		if(error == null) {
		    query = "SELECT USERNAME FROM USERS WHERE USERNAME='"+user+"';";
		    temp = ejbdb.selectSingleFieldValue(query, "USERNAME");
		
		    if(temp != null && temp.length()>1) {
			error = new StringBuffer("Sorry. Username is not avaiable!");
		    }
		}

		if(error == null) {
		    query = "SELECT EMAIL FROM USER_INFO WHERE EMAIL='"+email+"' AND STATUS='Y';";    
		    temp = ejbdb.selectSingleFieldValue(query, "EMAIL");
		    
		    if(temp != null && temp.length()>1 && !(email.equals("wli@3wcenter.com") || email.equals("aaindex@yahoo.com"))) {
			error = new StringBuffer("Sorry. E-mail["+email+"] has been registed by other user!");
		    }
		}
			
		if (error == null && !pass1.equals(pass2)) {
		    error = new StringBuffer("Password and Re-typed password are not same!");
		}

		if(error == null && !ck.checkSize("Password", pass1, 5, 20)) {
		    error = ck.getMessage();
		}

		if(error == null && !ck.checkEmail(email)) {
		    error = ck.getMessage();
		}

		if(error == null && fname.length() < 1) {
		    error = new StringBuffer("Please enter your First Name!");
		}
		if(error == null && lname.length() < 1) {
		    error = new StringBuffer("Please enter your Last Name!");
		}

		if(error == null && !ck.checkFormat("First Name", fname, format1)){
		    error = ck.getMessage();
		}

		if(error == null && !ck.checkFormat("Last Name", lname, format1)){
		    error = ck.getMessage();
		}

		if(error == null && month.length()==0) {
		    error = new StringBuffer("Please select your birth month!");
		}

		if(error == null && day.length()==0) {
		    error = new StringBuffer("Please select your birth date!");
		}

		if(error == null && year.length()==0) {
		    error = new StringBuffer("Please select your birth year!");
		}

		if(error == null && gender.length()==0) {
		    error = new StringBuffer("Please select your gender!");
		}

		if(error == null && user_edu.length()==0) {
		    error = new StringBuffer("Please select your education level!");
		}
		if(error == null && !ck.checkZipCode(zip)) {
		    error = ck.getMessage();
		}

		if(error == null && !img_key.equals(simg_key)) {
		    error = new StringBuffer("Please enter your image pin. Case sensitive!");
		}

		//========================================================================
		// save user info
		//========================================================================

		if(error == null) {
		    if(day.length()==1) {
			day = "0"+day;
		    }
		    if(month.length()==1) {
			month = "0"+month;
		    }
		    if(fname.indexOf("'") != -1) {
			fname = fname.replaceAll("'","''");
		    }
		    if(lname.indexOf("'") != -1) {
			lname = lname.replaceAll("'","''");
		    }

		    if(pass1.indexOf("'") != -1) {
			pass1 = pass1.replaceAll("'","''");
		    }

		    String activ_code = (""+System.currentTimeMillis()).substring(9);

		    query = 
			"INSERT INTO USER_INFO ("+
			"USERNAME, EMAIL,"+
			"FIRSTNAME, LASTNAME,"+
			"BIRTHDAY, JOINDAY, "+
			"GENDER, EDUCATION,"+
			"ZIPCODE, STATUS, FIELD11, FIELD12 ) VALUES ("+"'"+
			user+"','"+
			email+"','"+
			fname+"','"+
			lname+"','"+
			year+"-"+month+"-"+day+"',"+
			"'now','"+
			gender+"','"+
			user_edu+"','"+
			zip+"','N', '1', '"+activ_code+"');"+ 
			"INSERT INTO USERS(USERNAME,PASSWD) VALUES('"+user+"','"+pass1+"');"+
			"INSERT INTO USERROLES(USERNAME,USERROLES,ROLES)VALUES('"+user+"','1','Level-1');";
		
		    if(ejbdb.insert(query) !=1) {
			error = new StringBuffer("Save data error. Please check your data!");
		    }

		    if(error == null) {
			if(!sendVerifyEmail(email, fname, user, year+"-"+month+"-"+day, activ_code, "http://3wcenter.com")) {
			    error = new StringBuffer("Sendding e-mail error!");
			}
		    }
		    if(error == null) {
			sbf.append(messageActivation(email));
			sbf.append(activationForm(call_path, mid, saved_call_back));
			session.setAttribute("submit_id", null);
			return sbf;
		    }
		}
	    }
	    catch (IOException e) {
		error = new StringBuffer("Save data error! Please try again.");
	    }
	}

	String submit_id = ""+System.currentTimeMillis();
	
	try {
	    session.setAttribute("submit_id", submit_id);

	    sbf.append("\n<CENTER>");
	    sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	    sbf.append("\n<TABLE border='0' width='100%'>");
	    sbf.append("\n<TR><TD align='center'>");
	    sbf.append("\n<B>All fields are required.</B></TD></TR>");
	
	    if(error != null && error.length()>0) { 
		sbf.append("\n<TR><TD align='center'>");
		sbf.append("\n<img src=/images/star.gif border=0><I>"+error+"</I>");
		sbf.append("\n</TD></TR>");
	    }

	    sbf.append("\n<TR><TD></TD></TR>");
	    sbf.append("\n</TABLE>");
	    sbf.append("\n<TABLE border='0' width='100%'>");
	    sbf.append("\n<TR><TD align=right><B>3WCenter ID (User Name):</B></TD>");
	    sbf.append("\n<TD align='left'><input type='text' maxLength='20' name='user_name' value='"+user+"' size='20'></TD>");
	    sbf.append("\n</TR>");
	    sbf.append("\n<TR><TD align='right'><B>Password:</B></TD>");
	    sbf.append("\n<TD align='left'><input type='password' name='pass_word1' value='"+pass1+"' maxLength='20' size='20'></TD>");
	    sbf.append("\n</TR>");
	    sbf.append("\n<TR>");

	    sbf.append("\n<TD align='right'><B>Re-type Password:</B></TD>");
	    sbf.append("\n<TD align='left'>");
	    sbf.append("\n<INPUT maxLength='20' name='pass_word2' value='"+pass2+"' type='password' size='20'>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Current Email:</B></TD>");
	    sbf.append("\n<TD align='left'><INPUT maxLength='64' name='user_email' value='"+email+"' size='30'></TD>");
	    sbf.append("\n</TR>");
	    
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>First Name:</B></TD>");
	    sbf.append("\n<TD align='left'><INPUT maxLength='50' name='user_fname' value='"+fname+"' size='10'></TD>");
	    sbf.append("\n</TR>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Last Name:</B></TD>");
	    sbf.append("\n<TD align='left'><INPUT maxLength='50' name='user_lname' value='"+lname+"' size='10'></TD>");
	    sbf.append("\n</TR>");

	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Birthday:</B></TD>"); 
	    sbf.append("\n<TD>");
	    sbf.append("\n<SELECT name='op_age_month'>");
	    sbf.append("\n<OPTION value=''>Month</OPTION>");
	    sbf.append(MyHtml.getBirthMonthOption(month));
	    sbf.append("\n</SELECT>");
	    sbf.append("\n<SELECT name='op_age_day'>");
	    sbf.append("\n<OPTION value=''>Day</OPTION>");
	    sbf.append(MyHtml.getBirthDayOption(day));
	    sbf.append("\n</SELECT>");
	    sbf.append("\n<SELECT name='op_age_year'>");
	    sbf.append("\n<OPTION value=''>Year</OPTION>");
	    sbf.append(MyHtml.getBirthYearOption(year));
	    sbf.append("\n</SELECT>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");

	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Gender:</B></TD>"); 
	    sbf.append("\n<TD><SELECT name='op_sex'>");
	    sbf.append("\n<option value=''>---------</option>");
	    sbf.append(MyHtml.getGenderOption(gender));
	    sbf.append("\n</SELECT>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");

	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Education:</B></TD>"); 
	    sbf.append("\n<TD><SELECT name='op_edu'>");
	    sbf.append("\n<OPTION value=''>----------------</OPTION>");
	    sbf.append(MyHtml.getEducationOption(user_edu));
	    sbf.append("\n</SELECT>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");

	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Zip/postal code:</B></TD>"); 
	    sbf.append("\n<TD><input type='text' size='10' maxLength='10' name='user_zip' value='"+zip+"'>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");

	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='right'><B>Please enter&nbsp;</B>");
	    sbf.append("\n<IMG src='PasswordImage' width='80' height='25' border='1'></TD>");
	    sbf.append("\n<TD align='left'>");
	    sbf.append("\n<INPUT maxLength='20' name='img_key' value='' size='15' type='password'>");
	    sbf.append("&nbsp;<I><B>(*Case sensitive)</B></I></TD>");
	    sbf.append("\n</TR>");

	    sbf.append("\n</TABLE>");
	    sbf.append("<BR>");
	    sbf.append("\n<TABLE border='0' width='100%'>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='center'>");
	    sbf.append("\n<input type='submit' value='Submit' name='B1' style='font-size: 8pt'>");
	    sbf.append("\n<input type='reset' value='Reset' name='B2' style='font-size: 8pt'>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");
	    sbf.append("\n</TABLE>");

	    sbf.append("\n<TABLE>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='center'  style='font-size: 8pt' height='100'>");
	    sbf.append("\n<IFRAME src=/html/PrivacyPolicy.html width=500 height=120></IFRAME>");
	    sbf.append("\n</TD>");
	    sbf.append("\n</TR>");
	    sbf.append("\n</TABLE>");
	    sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	    sbf.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
	    sbf.append("\n<input type='hidden' name='aid' value='"+error_call_back+"'>");
	    sbf.append("\n</FORM>");
	    sbf.append("</CENTER>");
	}
	catch (Exception e) {
	    System.out.println("UserRegisterBean:Error:105"+e);
	}
	return sbf;
    }

    private boolean sendVerifyEmail (String to, String fname, String username, String userage, String active_code, String return_url) {
	String from    = "E-mail.Verification@3wcenter.com";
	String euser   = "Verification";
	String epass    = "LiNguyen5788";
	String subject = "3WCenter E-mail Verification";        

	String content =
	    "Welcome:"+fname+"!\n"+
	    "Please verify your account information:\n\n"+
	    "Username:\t"+username+"\n"+
	    "Account Activation Code : \t"+active_code+"\n\n"+
	    "Birthday:"+userage+" (Can not be changed.)\n"+
	    "You can modify your account information after you sign in.\n\n"+
	    "Please click this link to active your account\n"+
	    return_url+"/index/index.jsp?mid=verify&aid=1&uid="+username+"&vid="+active_code+"&sw=1101"+
	    "\nIf you can not see the above link, please type:\n"+
	    return_url+"/index/index.jsp?mid=verify&aid=1&uid="+username+"&vid="+active_code+"&sw=1014"+
	    "\nin your browser address field to verify.\nThank your!\n\n\n"+
	    "--3WCenter.com";


	try {
	    SendMail smail = new SendMail();
	    if(!smail.send(from, euser, epass, to, subject, content)) {
		return false;
	    }
	}
	catch (Exception e) {
	    return false;
	}     
	return true; 
    }

    public StringBuffer messageActivation(String email) {
	StringBuffer sbf = new StringBuffer ();
	sbf.append("<BR><B>Thank you!</B><BR>A activation code has been sent to:"+email+".");
	sbf.append("<BR>Please open your e-mail, <B>click</B> the link that ");
	sbf.append("3WCenter.com sent to you or <BR> type the activation code in this page to ");
	sbf.append("active your account.");
	sbf.append("<BR>");
	return sbf;
    }

    public StringBuffer activationForm(String call_path, String mid, String aid) {
	StringBuffer sbf = new StringBuffer ();
	sbf.append("<FORM method=post action='"+call_path+"'>");
	sbf.append("<TABLE cellSpacing=0 cellPadding=1 border=1 style='font-size: 10pt'>");
	sbf.append("<TR><TD>User Name:</TD>");
	sbf.append("<TD><input type=text name=uid value='' size=20 maxLength=50></TD></TR>");
	sbf.append("<TR><TD>Activation code:</TD>");
	sbf.append("<TD><input type=password name=vid value='' size=20 maxLength=20></TD></TR>");
	sbf.append("<TR><TD colspan=2 align=center><input type=submit name=B value=Submit style='font-size: 8pt'></TD></TR>");
	sbf.append("</TABLE>");
	sbf.append("<input type='hidden' name='mid' value='"+mid+"'>");
	sbf.append("<input type='hidden' name='aid' value='"+aid+"'>");
	sbf.append("</FORM>");
	return sbf;
    }
 
    public boolean activeUserAccount(HttpServletRequest request) {
	String uid = request.getParameter("uid");
	String vid = request.getParameter("vid");

	if(uid == null || vid == null || uid.length()<1 || vid.length()<1) {
	    return false;
	}

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    String query = "SELECT STATUS FROM USER_INFO WHERE USERNAME='"+uid+"' AND FIELD12='"+vid+"';";
	    String temp = ejbdb.selectSingleFieldValue(query, "STATUS");

	    if(temp == null || !(temp.equals("Y") || temp.equals("N"))) {
		return false;
	    }
	    else{
		if(temp.equals("N")) {
		    query ="UPDATE USER_INFO SET STATUS='Y' WHERE USERNAME='"+uid+"' AND FIELD12='"+vid+"';";
		    if(ejbdb.update(query) != 1) {
			return false;
		    }
		}
		else {
		    return true;
		}
	    }
	}
	catch (Exception e) {
	    return false;
	}
	return true;
    }
}

